#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Copyright © 启明星辰 版权所有
# @Time    : 2022/12/20 14:24
# @Author  : 胡浩浩
# @Email   : hu_haohao@venusgroup.com.cn
# @File    : show_funcs.py
# @IDE     : PyCharm
# @description :
import json
import re
import time

import jmespath
import requests
from pywebio.output import *
from pywebio.pin import *
from pywebio.session import eval_js

from backend.app.config import HOST
from commons.comms import close_pop
from frontend.menus import show_menus


def business_crud_data(action=None, item_id=None):
    """
        处理函数增删改查接口
    :param action:
    :param item_id:
    :return:
    """
    print(action)

    if action == "save":
        func_zh_name = pin.func_name
        func_code = pin.func_code
        func_params = pin.func_params
        func_name_exp = re.compile(r"def (.*?)\(")
        func_name_result = re.findall(func_name_exp, func_code)
        if func_name_result:
            try:
                func_en_name = func_name_result[0]
                exec(func_code, globals())
                exec(f'result={func_name_result[0]}({func_params})', globals())
                result = globals()["result"]
                result = f"{func_zh_name},执行成功:{result}"
                # 将数据存储到数据库
                data = {
                    "zh_name": func_zh_name,
                    "en_name": func_en_name,
                    "content": func_code,
                    "params": func_params
                }
                print(json.dumps(data, ensure_ascii=False))
                result = requests.post(
                    HOST + "/function/add",
                    json=data
                )
                print(result.json())
                toast(result.json().get("message"))
            except Exception as e:
                print(e)
                result = "函数脚本或参数有误,请保存正确的函数脚本"
                toast(result)
        return
    elif action == "update":
        func_zh_name = pin.func_name
        func_code = pin.func_code
        func_params = pin.func_params
        func_name_exp = re.compile(r"def (.*?)\(")
        func_name_result = re.findall(func_name_exp, func_code)
        if func_name_result:
            try:
                func_en_name = func_name_result[0]
                exec(func_code, globals())
                exec(f'result={func_name_result[0]}({func_params})', globals())
                result = globals()["result"]
                result = f"{func_zh_name},执行成功:{result}"
                data = {
                    "zh_name": func_zh_name,
                    "en_name": func_en_name,
                    "content": func_code,
                    "params": func_params
                }
                print(json.dumps(data, ensure_ascii=False))
                result = requests.put(
                    HOST + f"/function/{item_id}",
                    json=data
                )
                print(result.json())
                toast(result.json().get("message"))
            except Exception as e:
                print(e)
                result = "函数脚本或参数有误,请保存正确的函数脚本"
                toast(result)
    elif action == "run":
        func_code = pin.func_code
        func_params = pin.func_params
        func_name_exp = re.compile(r"def (.*?)\(")
        func_name_result = re.findall(func_name_exp, func_code)
        try:
            exec(func_code, globals())
            exec(f'result={func_name_result[0]}({func_params})', globals())
            result = globals()["result"]
        except Exception as e:
            print(e)
            result = "函数脚本或参数有误,请保存正确的函数脚本"
            toast(result)
        print(result)
        if not result:
            result = str(result)

        pin_update("func_result", value=result)
        return
    elif action == "delete":
        response = requests.delete(
            HOST + f"/function/{item_id}")
        print(response.json())
        toast(response.json()["message"])
        time.sleep(1)
        eval_js("window.location.reload();")
        return
    else:
        pass


def html_add_func():
    return popup('函数新增', [
        put_row([
            put_text("函数名称"),
            put_text("*").style("color:red"),
            put_input("func_name"),
        ], size="9% 1%"),
        put_row([
            put_text("函数脚本"),
            put_text("*").style("color:red"),
            put_textarea("func_code", code={
                'mode': "python",
                'theme': 'darcula'
            }, rows=20),
        ], size="9% 1%"),
        put_row([
            put_text("参数列表"),
            put_input("func_params"),
        ], size="10%"),
        put_row([
            put_text("运行结果"),
            put_textarea("func_result", rows=6),
        ], size="10%"),
        put_row([
            put_button("提交", onclick=lambda: business_crud_data("save"), small=True),
            put_button("调试", onclick=lambda: business_crud_data("run"), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="10% 80%"),

    ], size="large", closable=False)


def html_update_func(item):
    print(item)
    return popup('函数编辑', [
        put_row([
            put_text("函数名称"),
            put_text("*").style("color:red"),
            put_input("func_name", value=item[1]),
        ], size="9% 1%"),
        put_row([
            put_text("英文名称"),
            put_text("*").style("color:red"),
            put_input("func_en_name", value=item[2], readonly=True),
        ], size="9% 1%"),
        put_row([
            put_text("函数脚本"),
            put_text("*").style("color:red"),
            put_textarea("func_code", code={
                'mode': "python",
                'theme': 'darcula'
            }, rows=20, value=item[3]),
        ], size="9% 1%"),
        put_row([
            put_text("参数列表"),
            put_input("func_params", value=item[4]),
        ], size="10%"),
        put_row([
            put_text("运行结果"),
            put_textarea("func_result", rows=6),
        ], size="10%"),
        put_row([
            put_button("提交", onclick=lambda: business_crud_data("update", item[0]), small=True),
            put_button("调试", onclick=lambda: business_crud_data("run"), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="10% 80%"),

    ], size="large", closable=False)


def get_page_data(page: int = 1, size: int = 5, name: str = None):
    query_param = {
        "page": page,
        "size": size,
        "zh_name": name if name else ""
    }
    response = requests.get(HOST + "/function/page", params=query_param)

    print(1111111111111,response.text)
    variable_json = response.json().get("results")
    total = response.json().get("total")
    search_key = response.json().get("search_key")
    data_list = []
    if variable_json:
        data_list = jmespath.search("[].values(@)", variable_json)
    for v in data_list:
        exec_code = f"""
v[3]=put_collapse(v[2], [v[3]], open=False)
v.append(
    put_row([
        put_button("编辑", onclick=lambda: html_update_func({v}),small=True),
        None,
        put_button("删除", onclick=lambda: business_crud_data("delete",{v[0]}),color="danger",small=True),
    ]
    )
)
"""
        exec(exec_code)
    print(data_list)
    return total, page, search_key, data_list


def business_pages_data(current_page=1, page_size=10, name=None):
    page_size = 10
    print(f"当前第{current_page}页")
    if current_page < 1:
        current_page = 1
        toast("当前第一页")
        return
    total, current_page, search_key, data_list = get_page_data(current_page, page_size, name)
    if total <= page_size:
        total_page = 1
    else:
        total_page = int(total / page_size) + 1
    if current_page > total_page:
        current_page = total_page
        toast("当前最后一页")
        return
    table_header = [
        put_html('<h4 style="width:40px">编号</h4>'),
        put_html('<h4 style="width:150px">中文名称</h4>'),
        put_html('<h4 style="width:200px">英文名称</h4>'),
        put_html('<h4 style="width:400px">函数脚本</h4>'),
        put_html('<h4 style="width:70px">参数</h4>'),
        put_html('<h4 style="width:150px">创建时间</h4>'),
        put_html('<h4 style="width:150px">更新时间</h4>'),
        put_html('<h4 style="width:200px">操作</h4>')
    ]
    with use_scope("data_list", clear=True):
        put_tabs(
            [
                {
                    "title": "函数列表",
                    "content": [
                        put_button("新增", onclick=lambda: html_add_func(), small=True),
                        put_row(
                            [
                                put_text("函数名称: "),
                                put_input(name="func_search", placeholder="请输入函数中文名称进行查询",
                                          value=search_key),
                                None,
                                put_button("搜索", onclick=lambda: business_pages_data(name=pin.func_search),
                                           small=True),
                                put_button("重置",
                                           onclick=lambda: business_pages_data(), small=True),
                            ], size="8% 50% 5% 6%"
                        ),
                        put_table(data_list,
                                  header=table_header),
                        put_row([
                            put_text(
                                f"      每页{page_size}条      当前第{current_page}/{total_page}页       总共{total}条"),
                            put_button("上一页",
                                       onclick=lambda: business_pages_data(current_page - 1, page_size),
                                       small=True),
                            put_button("下一页",
                                       onclick=lambda: business_pages_data(current_page + 1, page_size),

                                       small=True),
                        ], size="40% 6% 6%"
                        )

                    ]
                }
            ], scope="data_list"
        )


def html_show_funcs():
    """
    内置函数
    """
    show_menus()
    business_pages_data()
